<?php
namespace App\Service\Admin\Yqh;

class FlowService extends BaseService
{
    //流程内容

    //列表
    public static function index($yqh_id, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbYqhFlow)
            ->where('del', 0);
        if ($yqh_id) {
            $db = $db->where('yqh_id', $yqh_id);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return self::toback(0, [], $total);
        }
        foreach ($res as &$v) {
            $yqh = self::dbConn(self::$dbYqh)->where('id', $v->yqh_id)->first();
            $v->yqh_title = $yqh ? $yqh->title : '-';
            $v->detail = mb_strlen($v->cnt)>10 ? mb_substr($v->cnt, 0, 10).'...' : $v->cnt;
            $v->starttime = $v->starttime ? $v->starttime : '-';
            $v->endtime = $v->endtime ? $v->endtime : '-';
        }
        return self::toback(0, '', $res, $total);
    }

    /**
     * 新增
     * @param array $pas
     */
    public static function add($yqh, $pas)
    {
        $yqhOne = self::dbConn(self::$dbYqh)->where('title', $yqh)->first();
        if (!$yqhOne) {
            return self::toback(-2, '邀请函错误');
        }
        $pas['yqh_id'] = $yqhOne->id;
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = self::dbConn(self::$dbYqhFlow)->insertGetId($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas
     */
    public static function modify($id, $yqh, $pas)
    {
        $yqhOne = self::dbConn(self::$dbYqh)->where('title', $yqh)->first();
        if (!$yqhOne) {
            return self::toback(-2, '邀请函错误');
        }
        $pas['yqh_id'] = $yqhOne->id;
        $pas['uptime'] = toDate();
        $up = self::dbConn(self::$dbYqhFlow)
            ->where('id', $id)
            ->update($pas);
        if (!$up) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    /**
     * 删除
     * @param int $id ID
     * return array
     */
    public static function del($id)
    {
        $res = self::dbConn(self::$dbYqhFlow)
            ->where('id', $id)
            ->update(['del' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }
}